import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useUserStore } from "@/store/user";
import { logout } from "@/common"

const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

instance.interceptors.request.use((config) => {
  // 进来判断有没有token，有的话带上让后端判断对应的用户
  let token = localStorage.getItem("token");
  if (token) {
    if (config.headers) {
      config.headers["Authorization"] = token;
    }
  }
  return config;
});

instance.interceptors.response.use(
  (response) => {
    const data = response.data as IResponse<any>;
    // token过期
    if (data.code === 401) {
      logout(undefined, () => {
        ElMessage.error("登录过期，请重新登录");
      });
    } else if (data.code !== 200) {
      ElMessage.error(data.message);
    }
    return response.data;
  },
  (err) => {
    ElMessage.error("请求失败,错误信息:" + err.message);
    Promise.reject(err);
  }
);

export default instance;
